package api

import (
	"encoding/json"

	"gitee.com/shiwjlinux/arm/apps/game"
	clients "gitee.com/shiwjlinux/arm/clients/restful"
	"gitee.com/shiwjlinux/arm/response"
	"github.com/gin-gonic/gin"
)

func (h *ApiHandler) Registry(appRouter gin.IRouter) {
	appRouter.POST("/sync", h.SyncGame)
}

func (h *ApiHandler) SyncGame(ctx *gin.Context) {
	// TODO:
	// https://gitlab.com/shiweijie1/go15/-/blob/main/devcloud-mini/cmdb/apps/secret/api/secret.go?ref_type=heads

	// http://172.20.12.12:9001/v1/ant_asset/games_list
	client := clients.NewClient("http://172.20.12.12:9001")
	client.Debug(true)
	res, err := client.C.R().Get("/v1/ant_asset/games_list")
	if err != nil {
		response.Failed(ctx, err)
	}

	set := game.NewSyncGameSet()
	if err := json.Unmarshal(res.Body(), set); err != nil {
		response.Failed(ctx, err)
	}

	h.logger.Debug().Msgf("sync game result: %d", len(set.GameItemInfo))

	// 2. 调用SyncGame接口，将数据同步到数据库

	_, err = h.svc.SyncGame(ctx, set, func(gr game.GameResponse) {
		h.logger.Debug().Msgf("sync game result: %v", gr)
		// TODO: 这里回调，创建一个websocket连接，并返回给前端
	})
	if err != nil {
		response.Failed(ctx, err)
		return
	}

	response.Success(ctx, nil)
}
